<template>
	<div class="container" >
		<div class="form-box" style="width:100%" >
			<el-form :model="productAttributeForm" :label-width="formLabelWidth">
				<el-header>
					<el-button type="primary" size="medium" @click="onSubmit" plain>保存</el-button>
					<el-button type="success" size="medium" @click="onReset" plain>重置数据</el-button>
					<el-button @click="func_back" size="medium" plain>返回</el-button>
				</el-header>
				<el-container style="width:100%;">
					<el-main >
<el-tabs type="border-card">
	<el-tab-pane label="商品属性">
		<el-divider content-position="left">商品属性配置</el-divider>
		<div :key="item" v-for="(item, index) in attrValueInput" >
			<el-form-item v-if="item.inputType === '11010001'" :label="item.attrName">
				<template #default="scope">
					<el-input v-model="item.attrId" v-if="false"/>
					<el-input class="handle-input" v-model="item.attrVal" />
				</template>
			</el-form-item>
			<el-form-item v-if="item.inputType === '11010002'" :label="item.attrName">
				<el-input v-model="item.clasId" v-if="false"/>
				<el-input v-model="item.attrId" v-if="false"/>
				<el-input v-model="item.inputType" v-if="false"/>
				<el-table :data="item.child" border class="table" header-cell-class-name="table-header" default-expand-all >
					<el-table-column prop="attrId" label="属性ID" v-if="false">
						<template #default="scope">
							<el-input class="handle-input" v-model="scope.row.attrValId" />
						</template>
					</el-table-column>
					<el-table-column prop="attrValue" label="商品属性" >
						<template #default="scope">
						{{scope.row.strAttrVal}}
						</template>
					</el-table-column>
					<el-table-column label="属性值">
						<template #default="scope">
							<el-input class="handle-input" v-model="scope.row.attrVal" />
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
		</div>
	</el-tab-pane>
	<el-tab-pane label="商品规格">
		<!-- <el-input v-model="productAttributeForm.productSpecParam" /> -->
		<el-input class="handle-input mr10" v-model="inputSpecColumn" />
		<el-button @click="func_add_CustomSpecColumn" plain>添加列</el-button>
		<el-button @click="func_add_CustomSpecData" plain>添加行</el-button>
		<el-button @click="func_clr_CustomSpecTable" plain>初始化表格</el-button>
		<el-button @click="func_cal_CustomSpecTable" plain>计算表格规格</el-button>
		<el-divider content-position="left">自定义规格</el-divider>
		<el-table :data="customSpecTableData" border style="width:100%;" header-cell-class-name="table-header">
			<!-- 动态列 -->
			<!-- <el-table-column  v-for="(item, index) in dynamicTableColumns" :key="index" :label="item.label" :prop="item.prop" fit :min-width="item.width">
				<template #default="scope">
					<el-input :key="1" fixed="right" sortable style="width:140px" maxlength="10" v-model="scope.row.inputSpecColumnVal0" />
				</template>
			</el-table-column> -->
			<el-table-column  v-for="(item, index) in dynamicTableColumns" :key="index" :label="item.label" :prop="item.prop" fit :min-width="item.width">
				<template #default="scope">
					<el-input fixed="right" style="width:140px" maxlength="10"  v-model="scope.row.inputSpecColumnVal2" v-if="index ===2"/>
					<el-input fixed="right" style="width:140px" maxlength="10"  v-model="scope.row.inputSpecColumnVal1" v-if="index ===1"/>
					<el-input fixed="right" style="width:140px" maxlength="10"  v-model="scope.row.inputSpecColumnVal0" v-if="index ===0"/>
				</template>
			</el-table-column>
			<el-table-column label="会员价格" prop="uPrice">
				<template #default="scope">
					<el-input style="width:140px" maxlength="10"  v-model="scope.row.uPrice" />
				</template>
			</el-table-column>
			<el-table-column label="价格" prop="price">
				<template #default="scope">
					<el-input style="width:140px" maxlength="10"  v-model="scope.row.price" />
				</template>
			</el-table-column>
			<el-table-column label="库存数量" prop="inventoryNumber">
				<template #default="scope">
					<el-input style="width:140px" maxlength="5"  v-model="scope.row.inventoryNumber" />
				</template>
			</el-table-column>
			<el-table-column label="锁定库存数量" prop="sockInventoryNumber">
				<template #default="scope">
					<el-input style="width:140px" maxlength="5"  v-model="scope.row.sockInventoryNumber" />
				</template>
			</el-table-column>
		</el-table>
	</el-tab-pane>
</el-tabs>
					</el-main>
				</el-container>
			</el-form>
		</div>
	</div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { findProductAttributeListByClassifyId, } from "../../../../api/hairmanager/productAttribute.js";
import { findProductInfoListById, saveProductInfo } from "../../../../api/hairmanager/products";

export default {
    name: "productSpecForm",
  	props:{
        selectValue: Object,
	},
	emits: ["productSpecFormData"],
    setup(props, cex){
		onMounted(() => {
		});
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
		const SUCCMESS_BUNDATA_DIALOG_MESSAGE = "添加数据成功";
		let id = route.query.id;
        const productSpecFormRef = ref(null);
        const productSpecForm = reactive({
			id: 0,
			specPic: '',
			productId: 0,
			price: 0,
			uPrice: 0,
			inventoryNumber: 0,
			sockInventoryNumber: 0,
			productSpecName: '',
			productSpecInfo: '',
        });
		const attrValueInput = ref([]);
		const productAttributeList = ref([]);
		const productAttributeForm = reactive({
			productSpecParam: [{}],
		});
		// 表单验证规则
        const productSpecFormRules = {
            productName: [
                { required: true, message: "请输入商品名称", trigger: "blur" },
            ],
            shipmentPrice : [
                { required: true, message: "请输入邮费", trigger: "blur" },
            ],
        };
		const classifyId = ref(0);
		// =========================================================================================
        const func_onLoad = () => {
            if (id > 0 ){
                findProductInfoListById(id).then((res) => {
                    if(res.code != 200) {
                        if(res.type == 0) {
                            ElMessage.warning(res.data.msg);
                        } else {
                            ElMessage.error(res.data.msg);
                        }
                    } else {
                        Object.keys(res.data).forEach((item) => {
                            productSpecForm[item] = res.data[item];
                        });
						classifyId.value = productSpecForm['productClassifyId'];
						func_loadClassifyAttribute();
                    }
                });
            }
        };
		func_onLoad();
        // 主业务处理 ========================================================================================= START
		const func_loadClassifyAttribute = () => {
			findProductAttributeListByClassifyId(classifyId.value).then((res) => {
				// productAttributeList.value = res.data;
				res.data.forEach((element) => {
					var obj = { attrId: 0, attrName: "", attrVal: "", attrValId: 0, clasId: 0, inputType: "",};
					obj['attrId'] = element['id'];
					obj['attrValId'] = 0;
					obj['attrVal'] = '';
					obj['attrName'] = element['attrName'];
					obj['inputType'] = element['inputType'];
					obj['clasId'] = classifyId.value;
					if(element['inputType'] === "11010002") {
						var child = [];
						element['productAttributeValues'].forEach((subElement) => {
							var obj = { attrId: 0, attrName: "", strAttrVal: "", attrVal: "", attrValId: 0, clasId: 0, inputType: "",};
							obj['attrId'] = element['id'];
							obj['attrValId'] = subElement['id'];
							obj['strAttrVal'] = subElement['attrValue'];
							obj['attrVal'] = '';//subElement['attrValue'];
							obj['attrName'] = element['attrName'];
							obj['inputType'] = element['inputType'];
							obj['clasId'] = classifyId.value;
							child.push(obj);
						});
						obj['child'] = child;
					} else {
						obj['child'] = [];
					}
					attrValueInput.value.push(obj);
				});
			});
		}
        // 提交
        const onSubmit = () => {
			var productSpecAttrParamList = [];
			attrValueInput.value.forEach((element) => {
				var productSpecAttrParam = {
					id: 0,
					productId: 0,
					productSpecId: 0,
					clasId: 0,
					attrId: 0,
					attrValId: 0,
					attrVal: "",
					strAttrValId: "",
				};
				Object.keys(productSpecAttrParam).forEach((item) => {
					productSpecAttrParam[item] = element[item];
				});
				if(element['child'].length >0 ){
					var obj2 = [];
					element['child'].forEach((item) => {
						obj2.push({attrValId: item['attrValId'], attrVal: item['attrVal']});
					});
					productSpecAttrParam['strAttrValId'] = obj2;
				};
				productSpecAttrParamList.push(productSpecAttrParam);
			});
			productSpecForm['productSpecAttrParamList'] = productAttributeForm;
			console.log("productSpecForm",productSpecForm);
        };
        // 重置
        const onReset = () => {
            
        };
        // 取消
        const func_back = () => {
            router.push({path: '/products', query:{id: 0}});
        };
		// 主业务处理 ========================================================================================= END
		// 规格图片处理 ========================================================================================= START
		const func_specPicSuccess = (res, file) => {
            if(file.response.code != 200) {
                if(res.type == 0) {
                    ElMessage.warning(res.data.msg);
                } else {
                    ElMessage.error(res.data.msg);
                }
            } else {
                var uploadFile = URL.createObjectURL(file.raw);
                productSpecForm['urlPic'] = file.response.data.imgUrl;
                ElMessage.success("上传成功");
            }
		};
		const func_beforeSpecPicUpload = (file) =>{
            const isJPG = file.type === 'image/jpeg';
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isJPG) {
                ElMessage.warning('上传图片只能是 JPG 格式!');
            };
            if (!isLt10M) {
                ElMessage.warning('上传图片大小不能超过 10MB!');
            }
            return isJPG && isLt10M;
		};
		// 规格图片处理 ========================================================================================= END
		// 自定义规格属性处理 ========================================================================================= START
		// const dynamicTableColumns = ref([
		// 	{prop: 'uPrice', label: '会员价格', type:'', width: '150' },
		// 	{prop: 'price', label: '价格', type:'', width: '150' },
		// 	{prop: 'inventoryNumber', label: '库存数量', type:'', width: '150' },
		// 	{prop: 'sockInventoryNumber', label: '锁定库存数量', type:'', width: '150' },
		// ]);
		const dynamicTableColumns = ref([]);
		const customSpecTableData = ref([]);
		const inputSpecColumn = ref("");
		const inputSpecColumnVal = ref("");
		let popColumnIndex = ref(0);
		const func_add_CustomSpecColumn = () => {
			if(inputSpecColumn.value.length === 0){
				ElMessage.warning('请填写自定义规格栏');
				return false;
			}
			if(popColumnIndex.value < 3) {
				var str_temp = 'inputSpecColumnVal'+''+popColumnIndex.value;
				dynamicTableColumns.value.unshift({prop: str_temp, label: inputSpecColumn.value, type: '', width: '150' });
				popColumnIndex.value = popColumnIndex.value+1;
			} else {
				ElMessage.warning('最高只能添加3个规格');
			}
		}
		const func_add_CustomSpecData = () => {
			switch (popColumnIndex.value) {
				case 0:
					ElMessage.warning('请添加一个商品规格');
					break;
				case 1:
					customSpecTableData.value.push({
						inputSpecColumnVal0: "",
						uPrice: 0,
						price: 0,
						inventoryNumber: 0,
						sockInventoryNumber: 0,
					});
					break;
				case 2:
					customSpecTableData.value.push({
						inputSpecColumnVal1: "",
						inputSpecColumnVal0: "",
						uPrice: 0,
						price: 0,
						inventoryNumber: 0,
						sockInventoryNumber: 0,
					});
					break;
				case 3:
					customSpecTableData.value.push({
						inputSpecColumnVal2: "",
						inputSpecColumnVal1: "",
						inputSpecColumnVal0: "",
						uPrice: 0,
						price: 0,
						inventoryNumber: 0,
						sockInventoryNumber: 0,
					});
					break;
				default:
					break;
			}
		};
		const func_clr_CustomSpecTable = () => {
			dynamicTableColumns.value = [];
			customSpecTableData.value = [];
			popColumnIndex.value = 0;
		};
		const func_cal_CustomSpecTable = () => {
			customSpecTableData.value.forEach((element) => {
				console.log("customSpecTableData", element);
				dynamicTableColumns.value.forEach((key) => {
					element[]
				})
			});
		}
		// 自定义规格属性处理 ========================================================================================= END
        // 业务数据监听
        watch(() => props.selectValue, (val) => {

        },{deep: true,immediate: true});
        return {
			// 系统变量
            formLabelWidth, productSpecFormRules, productSpecFormRef, productSpecForm, attrValueInput, productAttributeList, productAttributeForm,
			classifyId,
			// 主业务调用方法
            onSubmit, onReset, func_back, func_loadClassifyAttribute,	
			// 图片处理
			func_specPicSuccess, func_beforeSpecPicUpload,
			// 自定义规格表数据
			popColumnIndex,
			inputSpecColumn, dynamicTableColumns, customSpecTableData, func_add_CustomSpecColumn, func_add_CustomSpecData, func_clr_CustomSpecTable, func_cal_CustomSpecTable,
        };
    },
};
</script>
<style scoped>
.handle-box {
    margin-bottom: 20px;
}
.handle-select {
    width: 120px;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 70%;
    font-size: 14px;
}
.box-card {
	width:300px;
}
.mr10 {
    margin-right: 10px;
}
</style>